import sys,os
import pickle #pickle 是 Python 标准库中的一个模块，用于序列化和反序列化 Python 对象结构
import numpy as np
from dataset import mnist

def sigmoid(x):
    return 1/(1+np.exp(-x))

def softmax(a):
    c  = np.max(a)
    #  通过减去输入信号中的最大值，防止指数函数运算溢出
    exp_a = np.exp(a-c)
    sum_exp_a = np.sum(exp_a)
    y = exp_a / sum_exp_a
    return y
def get_data():
    (x_train, t_train), (x_test, t_test) = mnist.load_mnist(normalize=True,
                                                            flatten=True,
                                                            one_hot_label=False)
    return x_test,t_test
def init_network():
    with open("sample_weight.pkl", 'rb') as f:
        network = pickle.load(f)
    return network

# 三层神经网络的输出
def predict(network, x):
    W1, W2, W3 = network['W1'], network['W2'], network['W3']
    b1, b2, b3 = network['b1'], network['b2'], network['b3']
    a1 = np.dot(x, W1) + b1
    z1 = sigmoid(a1)
    a2 = np.dot(z1,W2)+b2
    z2 = sigmoid(a2)
    a3 = np.dot(z2,W3)+b3
    y = softmax(a3)
    return y

if __name__ == '__main__':
    x,t = get_data()
    network = init_network()
    batch_size = 100 # 批处理
    accuracy_cnt = 0
    for i in range(0,len(x),batch_size):
        x_batch = x[i:i+batch_size]
        y_batch = predict(network, x_batch)
        p = np.argmax(y_batch,axis=1) # 获取概率最高的元素索引
        accuracy_cnt += np.sum( p==t[i:i+batch_size]) # 预测准确，+1
    # 精度
    print("Accuracy:" + str(float(accuracy_cnt) / len(x)))



